package com.keson.spider;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range; 
public class DocUtil {
    public static void build(String  tmpFile, Map<String, String> contentMap, String exportFile){

//        InputStream inputStream = DocUtil.class.getClassLoader().getResourceAsStream(tmpFile);
//        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tmpFile);
    	
        HWPFDocument document = null;
        try {
        	InputStream inputStream = new FileInputStream(tmpFile);
            document = new HWPFDocument(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 读取文本内容
        Range bodyRange = document.getRange();
        // 替换内容
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }

        //导出到文件
        File efile = new File(exportFile);
        if(!efile.exists()) {
        	efile.getParentFile().mkdirs();
//        	try {
//				efile.createNewFile();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write(byteArrayOutputStream);
            OutputStream outputStream = new FileOutputStream(exportFile);
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
    	HashMap<String, String> map = new HashMap<String, String>();
    	map.put("index", "1");
    	map.put("sname", "张三");
    	map.put("y", "2021");
    	map.put("m", "03");
    	map.put("d", "23");
    	map.put("h", "10");
    	map.put("m", "41");
    	map.put("l", "四川省成都市武侯区");
    	map.put("ma", "5.2");
    	map.put("lat", "12.22");
    	map.put("lon", "36.32");
    	map.put("d", "15");
    	map.put("wname", "李四");
    	map.put("ename", "王五");
    	build("template/word.doc",map,"doc/第1期.doc");
    	
    	WordPrintUtil.print("doc/第1期.doc");
	}
}
